package com.google.bling.client.widget;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class ExpenseTable extends Composite {

  private Grid grid;
  private final List<String> participants;
  private final Map<String, Integer> costSums = new HashMap<String, Integer>();

  private void addCarryoverExpenses(Map<String, Integer> amounts) {
	addRow();
    int currentRow = grid.getRowCount() - 1;
    int currentColumn = 3;

    grid.setWidget(currentRow, 0, new Label("Balance"));
    for (String participant : participants) {
	  grid.setWidget(currentRow, currentColumn++, makeCost(amounts.get(participant)));
	  if (!costSums.containsKey(participant)) {
	    costSums.put(participant, 0);
	  }
	  costSums.put(participant, costSums.get(participant) + amounts.get(participant));
    }

  }

  private void addRow() {
	grid.resizeRows(grid.getRowCount() + 1);
  }

  private Widget makeCost(int cost) {
    Label l = new Label("$" + cost);
    if (cost >= 0) {
      l.addStyleName("positive");
    } else {
      l.addStyleName("negative");
    }
    return l;
  }

  public void addExpense(String date, String description, int totalCost,
      Map<String, Integer> amounts) {
    int currentRow = grid.getRowCount() - 1;
    int currentColumn = 0;
    grid.setWidget(currentRow, currentColumn++, new Label(date));
    grid.setWidget(currentRow, currentColumn++, new Label(description));
    grid.setWidget(currentRow, currentColumn++, makeCost(totalCost));

    for (String participant : participants) {
      grid.setWidget(currentRow, currentColumn++,
          new Label("$" + amounts.get(participant)));
      costSums.put(participant, costSums.get(participant) + amounts.get(participant));
    }
    addTotalRow(costSums);
  }

  public ExpenseTable(List<String> participants, Map<String, Integer> bbf) {
    this.participants = participants;
    for (String participant : participants) {
      costSums.put(participant, 0);
    }
    grid = new Grid(1, participants.size() + 3);
    grid.setCellPadding(2);
    grid.addStyleName("expense-table");
    int currentColumn = 0;
    grid.setWidget(0, currentColumn++, new Label("Date"));
    grid.setWidget(0, currentColumn++, new Label("Description"));
    grid.setWidget(0, currentColumn++, new Label("Cost"));

    for (String p : participants) {
      grid.setWidget(0, currentColumn++, new Label(p));
    }
    initWidget(grid);
    addCarryoverExpenses(bbf);
    addTotalRow(bbf);
  }

  private void addTotalRow(Map<String, Integer> bbf) {
    addRow();
    int currentRow = grid.getRowCount() - 1;
    int currentColumn = 3;
    grid.setWidget(currentRow, 0, new Label("Total"));
    for (String participant : participants) {
      grid.setWidget(currentRow, currentColumn++, makeCost(bbf.get(participant)));
    }
  }
}
